package com.siti.kindnessplatform.base.biz;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.siti.kindnessplatform.KindnessplatformApplication;
import com.siti.kindnessplatform.base.mapper.MaterialDetailMapper;
import com.siti.kindnessplatform.base.mapper.MaterialMapper;
import com.siti.kindnessplatform.base.po.Material;
import com.siti.kindnessplatform.base.po.MaterialDetail;
import com.siti.kindnessplatform.base.vo.ImgByteVo;
import com.siti.kindnessplatform.util.AddressLngLatExchange;

import sun.misc.BASE64Decoder;

@Service
@Transactional
public class MaterialBiz {
	
	@Resource
    private MaterialMapper materialMapper;
	@Resource
    private MaterialDetailMapper materialDetailMapper;
	
	public int save(Material material/*,String path*/) {
		try{
			if(material.getAddress()!=null&&material.getAddress()!=""){
				String lnglat = AddressLngLatExchange.getLngLat(material.getAddress());
//				System.out.println("lnglat:"+lnglat);
				if(lnglat!=null){
					String[] split = lnglat.split(",");//以逗号分割
					material.setLongitude(split[0]);
					material.setLatitude(split[1]);
				}
			}
//			MultipartFile[] files = material.getFiles();
//			String fileUrls = filesUpload(files,path);
//			if(fileUrls != null){
//				material.setPicUrl(fileUrls);
//			}
			materialMapper.insert(material);
			List<MaterialDetail> materialDetails=material.getMaterialDetails();
			if(materialDetails!=null){
				for(int i=0;i<materialDetails.size();i++){
					MaterialDetail materialDetail = materialDetails.get(i);
					materialDetail.setMaterialId(material.getId());
					materialDetailMapper.insert(materialDetail);
				}
			}
			return 1;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
	}
	
	public int savetest(Material material,String path) {
		try{
			if(material.getAddress()!=null&&material.getAddress()!=""){
				String lnglat = AddressLngLatExchange.getLngLat(material.getAddress());
//				System.out.println("lnglat:"+lnglat);
				if(lnglat!=null){
					String[] split = lnglat.split(",");//以逗号分割
					material.setLongitude(split[0]);
					material.setLatitude(split[1]);
				}
			}
			List<ImgByteVo> imgBytes = material.getImgBytes();
			String fileUrls="";
			if(imgBytes!=null){
				for (int i=0;i<imgBytes.size();i++) {
					String fileName = base64UpLoad(imgBytes.get(i).getImgByte(),path);
					fileUrls=fileUrls+fileName+",";
				}
				material.setPicUrl(fileUrls.substring(0,fileUrls.length() - 1));
			}
			if(fileUrls != null){
				material.setPicUrl(fileUrls);
			}
			materialMapper.insert(material);
			List<MaterialDetail> materialDetails=material.getMaterialDetails();
			if(materialDetails!=null){
				for(int i=0;i<materialDetails.size();i++){
					MaterialDetail materialDetail = materialDetails.get(i);
					materialDetail.setMaterialId(material.getId());
					materialDetailMapper.insert(materialDetail);
				}
			}
			return 1;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
	}
	
	public String filesUpload(@RequestParam("files") MultipartFile[] files,String path) throws IllegalStateException, IOException {
		
		// 构建上传文件的存放路径
		String destionation = getStr(path) + File.separator + "images";
		//System.out.println(destionation);
		String fileUrls="";
		// 如果文件不为空，写入上传路径，进行文件上传
		if (null != files && files.length > 0) {
			for (MultipartFile file : files) {
				// 测试MultipartFile接口的各个方法
				String fileUrl = saveFile(file, destionation);
				fileUrls=fileUrls+fileUrl+",";
			}
			return fileUrls.substring(0,fileUrls.length() - 1);
		} else {
			return null;
		}
	}
	
	/**
	 * 文件保存方法
	 * @param file
	 * @param destination
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private String saveFile(MultipartFile file, String destination) throws IllegalStateException, IOException {
		// 获取上传的文件名称，并结合存放路径，构建新的文件名称
		String filename = System.currentTimeMillis()+"_"+getUUIDFileName(file.getOriginalFilename());
		File filepath = new File(destination, filename);
		// 判断路径是否存在，不存在则新创建一个
		if (!filepath.getParentFile().exists()) {
			filepath.getParentFile().mkdirs();
		}
		// 将上传文件保存到目标文件目录
		file.transferTo(new File(destination + File.separator + filename));
		return filename;
	}
	
	public String getUUIDFileName(String fileName){
		// 将文件名的前面部分进行截取：xx.jpg   --->   .jpg
		int idx = fileName.lastIndexOf(".");
		String extention = fileName.substring(idx);
		String uuidFileName = UUID.randomUUID().toString().replace("-", "")+extention;
		return uuidFileName;
	}
	
	public String getStr(String str) {
        int index=str.lastIndexOf("/");
        index=str.lastIndexOf("/", index-1);
        index=str.lastIndexOf("/",index-1);
        index=str.lastIndexOf("/",index-1);
        return str.substring(0,index);
    }
	public String base64UpLoad(String imgByte,String path){
		try{  	           
        	// 构建上传文件的存放路径
    		String destionation = getStr(path) + File.separator + "images";
    		String dataPrix = "";	       
            if(imgByte == null || "".equals(imgByte)){
                throw new Exception("上传失败，上传图片数据为空");
            }else{
                String [] d = imgByte.split("base64,");
                if(d != null && d.length == 2){
                    dataPrix = d[0];
                }else{
                    throw new Exception("上传失败，数据不合法");
                }
            }
    		String suffix = "";
            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//编码的jpeg图片数据
                suffix = ".jpg";
                imgByte=imgByte.replaceAll("data:image/jpeg;base64,",""); 
            } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//编码的icon图片数据
                suffix = ".ico";
                imgByte=imgByte.replaceAll("data:image/x-icon;base64,",""); 
            } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//编码的gif图片数据
                suffix = ".gif";
                imgByte=imgByte.replaceAll("data:image/gif;base64,",""); 
            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//编码的png图片数据
                suffix = ".png";
                imgByte=imgByte.replaceAll("data:image/png;base64,",""); 
            }else{
                throw new Exception("上传图片格式不合法");
            }
        	BASE64Decoder decoder = new BASE64Decoder(); 
        	byte[] imageByte = null; 
        	imageByte = decoder.decodeBuffer(imgByte); 
    		for (int i = 0; i < imageByte.length; ++i) 
    		{ 
    			if (imageByte[i] < 0) {// 调整异常数据
    				imageByte[i] += 256;
    			} 
    		}
    		if (imageByte.length>0) {  
    			 //文件新名称 
    			String fileName = System.currentTimeMillis()+"_"+UUID.randomUUID().toString() + suffix; 
    			File f = new File(destionation + File.separator + fileName); 
    			// 将字符串转换成二进制，用于显示图片 
    			// 将上面生成的图片格式字符串 imgStr，还原成图片显示 
    			InputStream in = new ByteArrayInputStream(imageByte); 
    			FileOutputStream fos = new FileOutputStream(f); 
    			// BufferedOutputStream bos = new BufferedOutputStream(fos); 
    			byte[] buf = new byte[1024]; 
    			int length; 
    			length = in.read(buf, 0, buf.length); 
    			while (length != -1) { 
    				fos.write(buf,0,length); length = in.read(buf); 
    			} 
    			fos.flush(); 
    			fos.close(); 
    			in.close();
    			System.out.println("返回图片路径：" + fileName); 
    			return fileName; 
    		}
		}catch (Exception e) {
			e.printStackTrace();
        } 
		return null;
	}
}
